package com.ok.common.manager

import android.speech.tts.TextToSpeech
import android.speech.tts.UtteranceProgressListener
import android.speech.tts.Voice
import com.ok.common.base.AppContext
import com.ok.common.utils.LogUtils
import java.io.File
import java.util.*

class SpeechManager private constructor() : TextToSpeech.OnInitListener {

    companion object {
        private const val TAG = "SpeechManager"

        @Volatile
        private var instance: SpeechManager? = null

        fun get(): SpeechManager = instance ?: synchronized(this) {
            instance ?: SpeechManager().also { instance = it }
        }
    }

    // 语音速率 (0.5-2.0)
    private var speechRate = 1.0f

    // 语音音调 (0.5-2.0)
    private var pitch = 1.0f

    // 语音重复次数 (≥1)
    private var repeatCount = 1

    private var textToSpeech: TextToSpeech? = null
    private var ttsInitSuccess = false
    private val taskQueue = LinkedList<GenerateTask>()
    private var isGenerating = false

    private data class GenerateTask(
        val text: String,
        val outputFile: File,
        val listener: AudioGenerateListener?,
        val startTime: Long = System.currentTimeMillis()
    )

    interface AudioGenerateListener {
        fun onSuccess(file: File, costTimeMs: Long)
        fun onFailure(error: String)
    }

    /**
     * 设置语音速率
     * @param rate 速率值 (0.5-2.0)
     * @return SpeechManager 实例用于链式调用
     */
    fun setSpeechRate(rate: Float): SpeechManager {
        speechRate = rate.coerceIn(0.5f, 2.0f)
        textToSpeech?.setSpeechRate(speechRate)
        return this
    }

    /**
     * 设置语音音调
     * @param pitch 音调值 (0.5-2.0)
     * @return SpeechManager 实例用于链式调用
     */
    fun setPitch(pitch: Float): SpeechManager {
        this.pitch = pitch.coerceIn(0.5f, 2.0f)
        textToSpeech?.setPitch(this.pitch)
        return this
    }

    /**
     * 设置语音重复次数
     * @param count 重复次数 (≥1)
     * @return SpeechManager 实例用于链式调用
     */
    fun setRepeatCount(count: Int): SpeechManager {
        repeatCount = count.coerceAtLeast(1)
        return this
    }

    /**
     * 初始化TTS引擎
     */
    fun init() {
        textToSpeech = TextToSpeech(AppContext, this).apply {
            setOnUtteranceProgressListener(object : UtteranceProgressListener() {
                override fun onStart(utteranceId: String) = Unit

                override fun onDone(utteranceId: String) {
                    taskQueue.poll()?.let { task ->
                        val costTime = System.currentTimeMillis() - task.startTime
                        LogUtils.i(TAG, "生成完成，耗时: ${costTime}ms")
                        task.listener?.onSuccess(task.outputFile, costTime)
                    }
                    isGenerating = false
                    processNextTask()
                }

                override fun onError(utteranceId: String) {
                    taskQueue.poll()?.let { task ->
                        task.listener?.onFailure("生成失败")
                    }
                    isGenerating = false
                    processNextTask()
                }
            })
        }
    }

    /**
     * TTS引擎初始化回调
     */
    override fun onInit(status: Int) {
        ttsInitSuccess = status == TextToSpeech.SUCCESS
        if (ttsInitSuccess) {
            val voices = textToSpeech?.voices
            textToSpeech?.apply {
                language = Locale.CHINESE
                setSpeechRate(speechRate)
                setPitch(pitch)
                voices?.forEach { v ->
                    LogUtils.i("人声类型${v.name},${v.locale} ${v}")
                    if (v.name == "yue") {
                        setVoice(v)
                    }
                }
            }
            processNextTask()
        } else {
            taskQueue.clear()
        }
    }

    /**
     * 语音播报
     * @param text 播报的文本内容
     */
    fun speak(text: String) {
        if (!ttsInitSuccess) return
        repeat(repeatCount) {
            textToSpeech?.speak(text, TextToSpeech.QUEUE_ADD, null, null)
        }
    }

    /**
     * 生成WAV音频文件
     * @param text 转换的文本内容
     * @param outputFile 输出文件对象
     * @param listener 生成结果回调
     */
    fun generateWav(text: String, outputFile: File, listener: AudioGenerateListener? = null) {
        if (!ttsInitSuccess) {
            listener?.onFailure("TTS引擎未初始化")
            return
        }
        try {
            outputFile.parentFile?.mkdirs()
            if (outputFile.exists()) outputFile.delete()
            taskQueue.offer(GenerateTask(text, outputFile, listener))
            if (!isGenerating) processNextTask()
        } catch (e: Exception) {
            listener?.onFailure("文件创建失败: ${e.message}")
        }
    }

    /**
     * 处理下一个生成任务
     */
    private fun processNextTask() {
        if (taskQueue.isEmpty() || isGenerating) return
        taskQueue.peek()?.let { task ->
            isGenerating = true
            val result = textToSpeech?.synthesizeToFile(
                task.text, null, task.outputFile, UUID.randomUUID().toString()
            ) ?: TextToSpeech.ERROR
            if (result == TextToSpeech.ERROR) {
                taskQueue.poll()
                isGenerating = false
                task.listener?.onFailure("生成启动失败")
                processNextTask()
            }
        }
    }

    /**
     * 释放TTS资源
     */
    fun shutdown() {
        textToSpeech?.stop()
        textToSpeech?.shutdown()
        textToSpeech = null
        taskQueue.clear()
        isGenerating = false
        ttsInitSuccess = false
    }

}